package file

import (
	"archive/zip"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)
var fileList []string
func GetAllFile(pathname string) ([]string, error) {

	rd, err := ioutil.ReadDir(pathname)
	for _, fi := range rd {
		if fi.IsDir() {
			//fmt.Printf("[%s]\n", pathname+"\\"+fi.Name())
			GetAllFile(pathname + fi.Name() + "/")
		} else {
			//fmt.Println(fi.Name())
			fileList = append(fileList, pathname + fi.Name())
		}
	}
	return fileList, err
}
var zipfile []string
func Getzipfile(pathname string)([]string,error) {
	rd, err := ioutil.ReadDir(pathname)
	for _, fi := range rd {
		if fi.IsDir() {
			//fmt.Printf("[%s]\n", pathname+"\\"+fi.Name())
			Getzipfile(pathname + fi.Name() + "/")
		} else {
			//fmt.Println(fi.Name())
			zipfile = append(zipfile, pathname + fi.Name())
		}
	}
	return zipfile,err
}

func ReName(path string)  {
	sPath := strings.Split(path,".")
	newPath:= "."+sPath[1]+".zip"
	err:= os.Rename(path,newPath)
	fmt.Println(newPath)
	fmt.Println(err)
}
func UnpackRAR() error {
	currentDir, err := os.Getwd()
	if err != nil {
		return err
	}
	currentDir=currentDir+"\files"
	matches, err := filepath.Glob(currentDir + "\\*.rar")
	if err != nil {
		return err
	}
	for _, match := range matches {
		cmd := exec.Command("unrar", "x", "-ad", "-o+", match)
		err = cmd.Run()
		if err != nil {
			return err
		}
	}
	return nil
}
func Unzip(zipFile string, destDir string) error {
	zipReader, err := zip.OpenReader(zipFile)
	if err != nil {
		return err
	}
	defer zipReader.Close()

	for _, f := range zipReader.File {
		fpath := filepath.Join(destDir, f.Name)
		if f.FileInfo().IsDir() {
			os.MkdirAll(fpath, os.ModePerm)
		} else {
			if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
				return err
			}

			inFile, err := f.Open()
			if err != nil {
				return err
			}
			defer inFile.Close()

			outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
			if err != nil {
				return err
			}
			defer outFile.Close()

			_, err = io.Copy(outFile, inFile)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
